<?php
/**
 * Created by PhpStorm.
 * User: liu
 * Date: 2018/6/14
 * Time: 23:19
 */

namespace app\common\traits;
use think\Exception;


/**
 * model模型基础的curd操作
 * Trait BaseModel
 * @package app\common\traits
 */
trait Base{
    protected $error;
    protected $validate=null;
    protected $together=[];

    /**
     * 默认的软删除字段
     * @var array
     */
    protected $remove_field=['status'=>127];

    public function setRemoveField($name,$value){
        $this->remove_field=[$name=>$value];
    }

    protected function validate($param,$scene){
        if(is_null($this->validate)){
            return true;
        }
        $r=$this->validate->scene($scene)
            ->check($param);
        if($r===false){
            $this->error=$this->validate->getError();
        }
        return $r;
    }
    public function addHandler($param){
        $r=$this->validate($param,'add');
        if($r==false) return false;
        $r=$this->allowField(true)
            ->isUpdate(false)
            ->save($param);
        if($r===false)return $r;
        try {
            foreach ($this->together as $method => $value) {
                $flip_value = array_flip($value);
                $this->$method()->save(array_intersect_key($param,$flip_value));
            }
        }catch (Exception $e){
            $this->error=$e->getMessage();
            return false;
        }
        return $r;
    }
    public function editHandler($param){
        $r=$this->validate($param,'edit');
        if($r==false) return false;
        $r=$this->allowField(true)
            ->isUpdate(true)
            ->save($param);
        return $r;
    }
    public function remove($id){
        return $this->where(['id'=>$id])
            ->isUpdate(true)
            ->save($this->remove_field);
    }
    public function del($id){
        return $this->where(['id'=>$id])
            ->delete();
    }
}